package com.deer.wms.ASN.manage.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.deer.wms.ASN.manage.dao.AsnDetailMapper;
import com.deer.wms.ASN.manage.dao.AsnMasterMapper;
import com.deer.wms.ASN.manage.model.asn.*;
import com.deer.wms.ASN.manage.model.asn.CreateASN.CreateASN;
import com.deer.wms.ASN.manage.model.asn.CreateASN.CreateASNSKUDetail;
import com.deer.wms.ASN.manage.model.asn.CreateASN.CreateASNShipDetail;
import com.deer.wms.ASN.manage.model.buy.RequestBuyDetail;
import com.deer.wms.ASN.manage.model.file.AsnDetailFile;
import com.deer.wms.ASN.manage.model.file.AsnMasterFile;
import com.deer.wms.ASN.manage.service.*;
import com.deer.wms.base.system.dao.PackDetailMapper;
import com.deer.wms.base.system.dao.SupplierManageMapper;
import com.deer.wms.base.system.model.*;
import com.deer.wms.base.system.model.Item.ItemInfo;
import com.deer.wms.base.system.model.Pack.PackDetail;
import com.deer.wms.base.system.model.Supplier.SupplierManage;
import com.deer.wms.base.system.service.ItemInfoService;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.project.root.service.SuperServiceImpl;
import com.deer.wms.project.root.util.BeanUtils;
import com.deer.wms.project.root.util.DateUtils;
import com.deer.wms.project.root.util.HttpClient;
import com.deer.wms.project.root.util.StringUtils;
import com.deer.wms.review.manage.model.BillRecord;
import com.deer.wms.review.manage.service.BillRecordService;
import com.deer.wms.review.manage.service.CaseMasterService;
import com.deer.wms.system.manage.model.organization.Organization;
import com.deer.wms.system.manage.model.ware.WareInfo;
import com.deer.wms.system.manage.service.OrganizationService;
import com.deer.wms.system.manage.service.ValidatorService;
import com.deer.wms.system.manage.service.WareInfoService;
import com.deer.wms.ware.task.model.SO.SoDetail;
import com.deer.wms.ware.task.model.SO.SoMaster;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.ZoneOffset;
import java.util.*;

/**
 * Created by guo on 2020/01/03.
 */
@Service
@Transactional
public class AsnMasterServiceImpl extends SuperServiceImpl<AsnMasterMapper, AsnMaster> implements AsnMasterService {

    @Autowired
    private AsnMasterMapper asnMasterMapper;

    @Autowired
    private AsnMasterService asnMasterService;

    @Autowired
    private AsnDetailService asnDetailService;

    @Autowired
    private CaseMasterService caseMasterService;

    @Autowired
    private RequestBuyDetailService requestBuyDetailService;

    @Autowired
    private AsnMasterFileService asnMasterFileService;

    @Autowired
    private AsnDetailFileService asnDetailFileService;

    @Autowired
    private ValidatorService validatorService;

    @Autowired
    private BillRecordService billRecordService;

    @Autowired
    private WareInfoService wareInfoService;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private AsnShipDetailService asnShipDetailService;

    @Autowired
    private ItemInfoService itemInfoService;

    @Autowired
    private AsnDetailMapper asnDetailMapper;

    @Autowired
    private SupplierManageMapper supplierManageMapper;

    @Autowired
    private PackDetailMapper packDetailMapper;




    @Override
    public void deleteByBillNo(String billNo) {
        asnMasterMapper.deleteByBillNo(billNo);
    }

    @Override
    public void deleteByRequestBuyNo(String requestBuyBillNo){
        asnMasterMapper.deleteByRequestBuyNo(requestBuyBillNo);

    }

    @Override
    public List<AsnMasterDto> findList(AsnMasterCriteria criteria) {
        return asnMasterMapper.findList(criteria);
    }

    @Override
    public List<AsnMasterDto> findPdaList(AsnMasterCriteria criteria) {
        return asnMasterMapper.findPdaList(criteria);
    }


    @Override
    public void createAsnMaster(AsnData asnData, CurrentUser currentUser){

        AsnMaster asnMaster = asnData.getAsnMaster();
        String tableName = "asn_master";
        Integer nextId = validatorService.getNextId(tableName);

        String billNo = "ASN"+"-"+nextId;
        Integer createUserId = currentUser.getUserId();
        String createUserName = currentUser.getUserName();
        //0-等待审核 1-审核通过 -1-审核退回
        Integer state = 2;

        //调拨生成
        if(asnData.getBillSource()==4){
            BillRecord billRecord2 =billRecordService.findByBillNoAndType(asnMaster.getAllotBillNo(),41);//生成ASN

            billRecordService.updateBillRecord(billRecord2,currentUser);
        }
        //采购生成
        if(asnData.getBillSource()==0 ||asnData.getBillSource()==2 ){
            BillRecord billRecord2 =billRecordService.findByBillNoAndType(asnMaster.getRequestBuyBillNo(),10);//生成ASN
            billRecordService.updateBillRecord(billRecord2,currentUser);
        }

        //如果是草稿，则保存草稿记录
//        if(asnData.getInsertType()==-2){
//            BillRecord billRecord1 =new BillRecord();
//            billRecord1.setBillNo(billNo);
//            billRecord1.setRecordType(2);//ASN草稿
//            billRecord1.setCreateTime(createTime);
//            billRecord1.setCreateUserId(createUserId);
//            billRecord1.setCreateUserName(createUserName);
//            billRecordService.save(billRecord1);
//        }
//        //如果是新增，则添加新增记录
//        else if(asnData.getInsertType()==0) {
//            //通过草稿提交，则需要先把草稿删掉
//            String billNo1 = asnData.getAsnMaster().getBillNo();
//            if(billNo1 != null){
//                billNo = billNo1;
//                asnMasterService.deleteByBillNo(billNo1);
//                BillRecord billRecord1 =billRecordService.findByBillNoAndType(billNo,2);//ASN草稿
//                billRecordService.updateBillRecord(billRecord1,currentUser);
//            }
//            BillRecord billRecord3 = new BillRecord();
//            billRecord3.setBillNo(billNo);
//            billRecord3.setRecordType(Constants.BRECORD_ASN_CREATE);//生成ASN
//            billRecord3.setCreateTime(createTime);
//            billRecord3.setCreateUserId(createUserId);
//            billRecord3.setCreateUserName(createUserName);
//            billRecord3.setModifyTime(DateUtils.getNowDateTimeString());
//            billRecord3.setModifyUserId(createUserId);
//            billRecord3.setModifyUserName(createUserName);
//            billRecordService.save(billRecord3);
//            /**
//             * 添加审核流
//             */
//            //        -1不通过  0-流转中 1-已通过
//            state = caseMasterService.createCase(billNo, 2, currentUser.getUserId(), asnMaster.getWareId(),asnMaster.getOrganizationId());
//            BillRecord billRecord1 =new BillRecord();
//            billRecord1.setBillNo(billNo);
//            billRecord1.setRecordType(Constants.BRECORD_ASN_CHECK);//ASN审核
//            billRecord1.setCreateTime(createTime);
//            billRecord1.setCreateUserId(createUserId);
//            billRecord1.setCreateUserName(createUserName);
//            billRecordService.save(billRecord1);
//            if(state ==1){
//                billRecord1.setModifyTime(DateUtils.getNowDateTimeString());
//                billRecord1.setModifyUserId(createUserId);
//                billRecord1.setModifyUserName(createUserName);
//                billRecordService.updateById(billRecord1);
//            }
//        }

        //新增Master
        asnMaster.setCreateUserId(createUserId);
        asnMaster.setCreateUserName(createUserName);
        asnMaster.setState(state);
        asnMaster.setInsertType(asnData.getInsertType());
        asnMaster.setBillSource(asnData.getBillSource());
        if (StringUtils.isNotEmpty(asnMaster.getBillNo())) {
            asnMasterService.updateById(asnMaster);
        } else {
            asnMaster.setBillNo(billNo);
            asnMasterService.save(asnMaster);
        }


        //新增detail
        List<AsnDetail> asnDetails = asnData.getAsnDetails();
        for (int i = 0; i < asnDetails.size(); i++) {
            String detailNo = billNo + "-" + (i + 1);
            AsnDetail asnDetail = asnDetails.get(i);
            asnDetail.setBillNo(billNo);
            asnDetail.setId(null);
            asnDetail.setDetailNo(detailNo);
            asnDetailService.save(asnDetail);
            //更新采购单的ASN数量
            String requestDetailDetailNo = asnDetail.getRequestDetailDetailNo();
            RequestBuyDetail requestBuyDetail = requestBuyDetailService.findByDetailNo(requestDetailDetailNo);
            if (requestBuyDetail != null) {
                requestBuyDetail.setAsnQuantity(asnDetail.getExpectQuantity() + requestBuyDetail.getAsnQuantity());
                requestBuyDetailService.updateById(requestBuyDetail);
            }
        }

        //送货单 跟TMS相关
//        List<AsnShipDetail> asnShipDetails = asnData.getAsnShipDetails();
//        if (asnShipDetails != null && asnShipDetails.size() > 0) {
//            for (AsnShipDetail asnShipDetail : asnShipDetails) {
//                asnShipDetail.setBillNo(billNo);
//                asnShipDetail.setCreateTime(DateUtils.getNowDateTimeString());
//                asnShipDetailService.save(asnShipDetail);
//            }
//        }
    }


    /**
     * 归档
     * @param billNo
     * @param currentUser
     */
    @Override
    public void createFile(String billNo, CurrentUser currentUser){
        AsnMaster asnMaster = asnMasterService.findBy("bill_no",billNo);
        //状态为 ASN完成状态
        if(asnMaster.getAsnState() !=3){
            throw new ServiceException(CommonCode.ASN_FILE_ERROR);
        }
        Integer fileUserId = currentUser.getUserId();
        String fileUserName = currentUser.getUserName();
        String fileTime = DateUtils.getNowDateTimeString();

        BillRecord billRecord =new BillRecord();
        billRecord.setBillNo(billNo);
        billRecord.setRecordType(6);//ASN归档
        billRecord.setCreateTime(fileTime);
        billRecord.setCreateUserId(fileUserId);
        billRecord.setCreateUserName(fileUserName);
        billRecordService.save(billRecord);
        AsnMasterFile asnMasterFile = new AsnMasterFile();
        BeanUtils.copyProperties(asnMaster, asnMasterFile);

        asnMasterFile.setFileUserId(fileUserId);
        asnMasterFile.setFileUserName(fileUserName);
        asnMasterFile.setFileTime(fileTime);
        asnMasterFileService.save(asnMasterFile);
        List<AsnDetail> asnDetails = asnDetailService.findByBillNo(billNo);

//        BeanUtils.copyProperties(asnDetails, asnDetailFile);
        for(int i=0;i<asnDetails.size();i++){
            AsnDetailFile asnDetailFile = new AsnDetailFile();
            asnDetailFile.setBillNo(asnDetails.get(i).getBillNo());
            asnDetailFile.setRequestDetailDetailNo(asnDetails.get(i).getRequestDetailDetailNo());
            asnDetailFile.setDetailNo(asnDetails.get(i).getDetailNo());
            asnDetailFile.setItemCode(asnDetails.get(i).getItemCode());
            asnDetailFile.setItemName(asnDetails.get(i).getItemName());
            asnDetailFile.setPackDetailId(asnDetails.get(i).getPackDetailId());
            asnDetailFile.setPackDescribe(asnDetails.get(i).getPackDescribe());
            asnDetailFile.setAcceptQuantity(asnDetails.get(i).getAcceptQuantity());
            asnDetailFile.setExpectQuantity(asnDetails.get(i).getExpectQuantity());
            asnDetailFile.setMemo(asnDetails.get(i).getMemo());
            asnDetailFile.setAcceptTime(asnDetails.get(i).getAcceptTime());
            asnDetailFile.setState(asnDetails.get(i).getState());
            asnDetailFile.setAsnUdfDs1(asnDetails.get(i).getAsnUdfDs1());
            asnDetailFile.setAsnUdfDs2(asnDetails.get(i).getAsnUdfDs2());
            asnDetailFile.setAsnUdfDs3(asnDetails.get(i).getAsnUdfDs3());

            asnDetailFileService.save(asnDetailFile);


        }
        asnMasterService.deleteByBillNo(billNo);
        BillRecord billRecord1 = billRecordService.findByBillNoAndType(billNo,6);//ASN归档
        billRecord1.setModifyUserId(fileUserId);
        billRecord1.setModifyUserName(fileUserName);
        billRecord1.setModifyTime(DateUtils.getNowDateTimeString());
        billRecordService.updateById(billRecord1);
    }

    @Override
    public void createASN(CreateASN createASN, CurrentUser currentUser) {
        AsnMaster asnMaster = new AsnMaster();
        String tableName = "asn_master";
        Integer nextId = validatorService.getNextId(tableName);

        String billNo =createASN.getBillNo();
        Integer createUserId = currentUser.getUserId();
        String createUserName = currentUser.getUserName();
        String createTime = DateUtils.getNowDateTimeString();

        String wareCode = createASN.getWareCode();
        String orgCode = createASN.getOrgCode();
        WareInfo wareInfo = wareInfoService.getOneByField("ware_code",wareCode);

        Organization organization = organizationService.findBy("organization_code",orgCode);

        asnMaster.setAsnState(0);
        asnMaster.setBillNo(billNo);
        asnMaster.setCreateUserId(createUserId);
        asnMaster.setCreateUserName(createUserName);
        asnMaster.setWareId(wareInfo.getWareId());
        asnMaster.setWareName(wareInfo.getWareName());
        asnMaster.setWareId(wareInfo.getWareId());
        asnMaster.setWareCode(wareInfo.getWareCode());
        asnMaster.setOrganizationCode(organization.getOrganizationCode());
        asnMaster.setOrganizationName(organization.getOrganizationName());
        asnMaster.setOrganizationId(organization.getOrganizationId());
        asnMaster.setRequestBuyBillNo(createASN.getBillNo());
        asnMaster.setInsertType(4);
        asnMasterService.save(asnMaster);
        List<CreateASNShipDetail> shipDetails = createASN.getShipList();
        if(shipDetails!=null){
            for (CreateASNShipDetail createASNShipDetail:shipDetails
            ) {
                AsnShipDetail asnShipDetail = asnShipDetailService.findBy("ship_bill_code",createASNShipDetail.getShipBillCode());
                if(asnShipDetail==null){
                    asnShipDetail = new AsnShipDetail();
                    asnShipDetail.setBillNo(asnMaster.getBillNo());
                    asnShipDetail.setShipBillCode(createASNShipDetail.getShipBillCode());
                    asnShipDetail.setShipCode(createASNShipDetail.getShipCode());
                    asnShipDetailService.save(asnShipDetail);
                }else {

                }
            }
        }
        List<CreateASNSKUDetail> asnskuDetails = createASN.getSkuList();
        for(int i = 0;i<asnskuDetails.size();i++){
            CreateASNSKUDetail  createASNSKUDetail = asnskuDetails.get(i);

            ItemInfo itemInfo = itemInfoService.findBy("item_code",createASNSKUDetail.getSkuCode());
            if(itemInfo==null){
                itemInfo = new ItemInfo();
                itemInfo.setItemCode(createASNSKUDetail.getSkuCode());
                itemInfo.setItemName(createASNSKUDetail.getSkuName());
                itemInfo.setImgUrl(createASNSKUDetail.getImgUrl());
                itemInfo.setOrganizationId(organization.getOrganizationId());
                itemInfo.setPackCode("sys_pack");
                itemInfoService.save(itemInfo);
            }else if(itemInfo.getImgUrl()==null || itemInfo.getImgUrl().equals("")   ){
                itemInfo.setImgUrl(createASNSKUDetail.getImgUrl());
                itemInfoService.updateById(itemInfo);
            }
            AsnDetail asnDetail = new AsnDetail();
            asnDetail.setBillNo(asnMaster.getBillNo());
            asnDetail.setDetailNo(asnMaster.getBillNo()+(i+1));
            asnDetail.setItemCode(createASNSKUDetail.getSkuCode());
            asnDetail.setItemName(createASNSKUDetail.getSkuName());
            asnDetail.setSpec(createASNSKUDetail.getSpec());
            asnDetail.setModel(createASNSKUDetail.getModel());
            asnDetail.setImgUrl(createASNSKUDetail.getImgUrl());
            asnDetail.setPackCode("sys_pack");
            asnDetail.setPackDetailId(166);
            asnDetail.setPackDescribe("each");
            asnDetail.setTransRatio(1.0);
            asnDetail.setExpectQuantity(createASNSKUDetail.getQuantity());
            asnDetailService.save(asnDetail);

        }

    }

    @Override
    public AsnMasterDto findByBillNo(String billNo) {
        return asnMasterMapper.findByBillNo(billNo);
    }

    @Override
    public AsnMaster  findSoByBillNo( String billNo,  String wareCode) {
        return asnMasterMapper.findSoByBillNo(billNo,wareCode);
    }

    @Override
    public AsnMaster findBy(String field, String value) {
        QueryWrapper<AsnMaster> qw = new QueryWrapper<>();
        return getOne(qw.eq(field, value));
    }

    @Override
    public String savePurchaseOrder() {

        try {
            //请求token
            System.out.println("请求token");
            MultiValueMap<String, String> stringMultiValueMap = new LinkedMultiValueMap<>();
            stringMultiValueMap.add("client_id", "KingdeeK3_Rggy_AppClient_Test");
            stringMultiValueMap.add("client_secret", "TekE%dAISMCvwk7V");
            stringMultiValueMap.add("grant_type", "password");
            stringMultiValueMap.add("username", "epichust");
            stringMultiValueMap.add("password", "hK@vmz0YI1e^thtB");
            String tokenUrl = "https://syecrg.sieyuan.com:44310/connect/token";
            String clientRg = HttpClient.clientRg(tokenUrl, HttpMethod.POST, stringMultiValueMap);
            JSONObject jsonObject = JSONObject.parseObject(clientRg);
            String token = jsonObject.getString("access_token");
            System.out.println("token" + token);

            if(token != null){

                Map<String, String> map1 = new HashMap<>();
//                Calendar calendar = Calendar.getInstance();
//                calendar.setTime(new Date());
//                calendar.add(Calendar.DAY_OF_MONTH,-3);
//                map1.put("dateFrom", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                map1.put("dateFrom", "2022-05-11");
                //调用erp接口获取数据
                CloseableHttpClient client = HttpClients.createDefault();
                URIBuilder uriBuilder = new URIBuilder("https://syecrg.sieyuan.com:44398/api/Epichust/GetAllIMInSourceBills");
                HttpPost post = new HttpPost(uriBuilder.build());
                StringEntity myEntity = new StringEntity(JSON.toJSONString(map1), "UTF-8");// 构造请求数据
                post.setHeader("Content-Type", "application/json");
                post.addHeader("Authorization", "Bearer " + token);
                post.setEntity(myEntity);// 设置请求体
                String responseContent = null; // 响应内容
                CloseableHttpResponse response = null;
                try {
                    response = client.execute(post);
                    HttpEntity entity = response.getEntity();
                    if (response.getStatusLine().getStatusCode() == 200) {
                        String content = EntityUtils.toString(entity, "UTF-8");
                        List<PurchaseOrderBO> po = (List<PurchaseOrderBO>) JSON
                                .parseArray(content, PurchaseOrderBO.class);
                        System.out.println("s=========="+content);
                        if(po.size() != 0){
                            List<AsnDetail> asnDetails = new ArrayList<>();
                            List<AsnMaster> asnMasters = new ArrayList<>();
                            List<ItemInfo> itemInfos = new ArrayList<>();
                            for(PurchaseOrderBO bo : po){

                                //先判断抓取的数据在数据库中是否存在
                                QueryWrapper<AsnMaster> qw = Wrappers.query();
                                Map<String, Object> map = new HashMap<>();
                                map.put("bill_no", bo.getBillNo());
                                map.put("bill_type", bo.getBillTypeId());
                                AsnMaster info = asnMasterMapper.selectOne(qw.allEq(map, false));
                                if(info == null){
                                    AsnMaster asnMaster = new AsnMaster();
//                            System.out.println("开始保存了主表信息");
                                    asnMaster.setOrganizationId(bo.getId());//主键
                                    asnMaster.setBillType(bo.getBillTypeId());//单据类型ID
                                    asnMaster.setUda1(bo.getBillTypeName());//单据类型
                                    asnMaster.setBillNo(bo.getBillNo());//单据编号
                                    asnMaster.setExpectTime(bo.getBillDate());//单据日期
//                                    asnMaster.setAsnState(bo.getBillStatus());//工业单据状态
                                    asnMaster.setAsnState(0);//工业单据状态
                                    asnMaster.setUda2(bo.getBillClosed() == null || bo.getBillClosed() ==false ? "0":"1");//关闭状态
                                    asnMaster.setSupplierId(bo.getSupplierId());//供应商ID
                                    asnMaster.setSupplierName(bo.getSupplierName());//供应商名称
                                    asnMaster.setCreateUserId(bo.getCustomerId());//客户ID
                                    asnMaster.setAsnUdfHs2(bo.getCustomerName());//客户名称
                                    asnMaster.setModifyUserId(bo.getDeptId());//部门ID
                                    asnMaster.setUda3(bo.getDeptName());//部门名称
                                    asnMaster.setMemo(bo.getRemark());//备注
                                    asnMaster.setWareId(285);//仓库ID
                                    asnMaster.setOrganizationName(bo.getOrderBillTypeId() == null ? null : bo.getOrderBillTypeId().toString());
                                    asnMaster.setWareCode(bo.getOrderBillId() == null ? null : bo.getOrderBillId().toString());
                                    asnMaster.setRequestBuyBillNo(bo.getOrderBillNo());
                                    asnMaster.setAsnUdfHs3(bo.getAgreementNo());
                                    asnMaster.setAsnType(getAsnType(bo));
                                    QueryWrapper<SupplierManage> qw2 = Wrappers.query();
                                    Map<String, Object> map2 = new HashMap<>();
                                    map2.put("supplier_id", bo.getSupplierId());
//                            map2.put("supplier_name", bo.getSupplierName());
                                    SupplierManage info2 = supplierManageMapper.selectOne(qw2.allEq(map2, false));
                                    if(info2 == null){
                                        SupplierManage supplierManage = new SupplierManage();
                                        supplierManage.setSupplierId(bo.getSupplierId());
                                        supplierManage.setSupplierName(bo.getSupplierName());
                                        supplierManageMapper.insert(supplierManage);
                                    }
                                    List<PurchaseOrderDetailBO> purchaseOrderDetailBOS = bo.getDetails();
                                        Integer i = 1;
                                        for(PurchaseOrderDetailBO purchaseOrderDetailBO :purchaseOrderDetailBOS){
                                            AsnDetail asnDetail = new AsnDetail();
                                            asnDetail.setBillNo(asnMaster.getBillNo());//ASN单号
                                            asnDetail.setPackDetailId(purchaseOrderDetailBO.getUnitId());//基本单位ID
                                            asnDetail.setPackDescribe(purchaseOrderDetailBO.getUnitName());//单位

                                            QueryWrapper<PackDetail> packQw = Wrappers.query();
                                            Map<String, Object> packMap = new HashMap<>();
                                            packMap.put("pack_detail_id", purchaseOrderDetailBO.getUnitId());
                                            packMap.put("pack_describe", purchaseOrderDetailBO.getUnitName());
                                            PackDetail pack = packDetailMapper.selectOne(packQw.allEq(packMap, false));
                                            if(pack == null){
                                                PackDetail de = new PackDetail();
                                                de.setPackDetailId(purchaseOrderDetailBO.getUnitId());
                                                de.setPackDescribe(purchaseOrderDetailBO.getUnitName());
                                                packDetailMapper.insert(de);
                                            }

                                            asnDetail.setExpectPackDetailId(purchaseOrderDetailBO.getItemId());//物料ID
                                            asnDetail.setItemCode(purchaseOrderDetailBO.getItemNumber());//物料编码
                                            asnDetail.setItemName(purchaseOrderDetailBO.getItemName());//物料名称
                                            asnDetail.setUda1(purchaseOrderDetailBO.getItemModel());//规格型号
                                            asnDetail.setAcceptPackDetailId(purchaseOrderDetailBO.getAuxPropClassId());//辅助属性类别ID
                                            asnDetail.setUpperPackDetailId(purchaseOrderDetailBO.getAuxPropId());//辅助属性ID
                                            asnDetail.setAsnUdfDs1(purchaseOrderDetailBO.getAuxPropName());//辅助属性
                                            asnDetail.setDetailNo(asnMaster.getBillNo()+ "-" + i);
//                                    asnDetail.setModifyUserId(purchaseOrderDetailBO.getAuxUnitId());//单位ID
//                                    asnDetail.setRequestDetailDetailNo(purchaseOrderDetailBO.getAuxUnitName());//单位
                                            //批次管理
                                            asnDetail.setUda2(purchaseOrderDetailBO.getBatchManager()==null || purchaseOrderDetailBO.getBatchManager() == false ? "0" : "1");
                                            asnDetail.setModel(purchaseOrderDetailBO.getBatchNo());//批号
//                                    asnDetail.setTransRatio(purchaseOrderDetailBO.getAuxQty());//数量
                                            if(bo.getBillTypeId() == 702){
                                                asnDetail.setExpectQuantity(purchaseOrderDetailBO.getQcQty());//基本单位数量
                                                ItemInfo itemInfo = itemInfoService.getOneByField("item_code", purchaseOrderDetailBO.getItemNumber());
                                                if(!"SYS-CHECK".equals(itemInfo.getQcTacticCode())){
                                                    itemInfo.setQcTacticCode("SYS-CHECK");
                                                    itemInfos.add(itemInfo);
                                                }
                                            }else {
                                                asnDetail.setExpectQuantity(purchaseOrderDetailBO.getQty());//基本单位数量
                                                asnDetail.setAcceptQuantity(purchaseOrderDetailBO.getQcQty());//基本单位待检数量
                                            }
                                            asnDetail.setCreateUserId(purchaseOrderDetailBO.getRowIndex());//基本单位ID
//                                    asnDetail.setAcceptTransRatio(purchaseOrderDetailBO.getAuxCommitQty());//已执行数量
//                                    asnDetail.setUpperQuantity(purchaseOrderDetailBO.getCommitQty());//基本单位已执行数量
//                                    asnDetail.setUda3(purchaseOrderDetailBO.getPlanModeId().toString());//计划模式ID
                                            asnDetail.setPackCode(purchaseOrderDetailBO.getMtoNo());//计划跟踪号

                                            //目标单据红蓝字
                                            asnDetail.setExpectPackDescribe(purchaseOrderDetailBO.getTargetBillROB()==null || purchaseOrderDetailBO.getBatchManager() == false ? "0" : "1");
                                            asnDetail.setUpperPackDescribe(purchaseOrderDetailBO.getTargetBillTypeId().toString());
                                            asnDetail.setAcceptPackDescribe(purchaseOrderDetailBO.getShelfLifeManager() ==null || purchaseOrderDetailBO.getShelfLifeManager() == false ? "0" : "1");
                                            asnDetail.setAsnUdfDs2(purchaseOrderDetailBO.getProductionDate());
                                            asnDetail.setAsnUdfDs3(purchaseOrderDetailBO.getShelfLifeDays().toString());
                                            asnDetail.setUda3(purchaseOrderDetailBO.getVersion());
                                            asnDetail.setAllotDetailNo(purchaseOrderDetailBO.getLatestVersion());
                                            i++;
                                            asnDetails.add(asnDetail);
                                        }
                                    asnMasters.add(asnMaster);
                                }

                            }
                            asnMasterService.saveBatch(asnMasters);
                            System.out.println("保存了主表信息");

                            asnDetailService.saveBatch(asnDetails);
                            System.out.println("保存了子表信息");

                            if(itemInfos.size() != 0){
                                itemInfoService.saveOrUpdateBatch(itemInfos);
                            }
                        }


                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }  finally {
                    try {
                        if (response != null)
                            response.close();

                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (client != null)
                                client.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return null;
    }

    @Override
    public void createAsnMaster2(AsnData asnData, CurrentUser currentUser) {
        AsnMaster asnMaster = asnData.getAsnMaster();
        String tableName = "asn_master";
        Integer nextId = validatorService.getNextId(tableName);

        String billNo = "ASN"+"-"+nextId;
        Integer createUserId = currentUser.getUserId();
        String createUserName = currentUser.getUserName();
        //0-等待审核 1-审核通过 -1-审核退回
        Integer state = 2;

        //调拨生成
        if(asnData.getBillSource()==4){
            BillRecord billRecord2 =billRecordService.findByBillNoAndType(asnMaster.getAllotBillNo(),41);//生成ASN

            billRecordService.updateBillRecord(billRecord2,currentUser);
        }
        //采购生成
        if(asnData.getBillSource()==0 ||asnData.getBillSource()==2 ){
            BillRecord billRecord2 =billRecordService.findByBillNoAndType(asnMaster.getRequestBuyBillNo(),10);//生成ASN
            billRecordService.updateBillRecord(billRecord2,currentUser);
        }

        //新增Master
        asnMaster.setCreateUserId(createUserId);
        asnMaster.setCreateUserName(createUserName);
        asnMaster.setState(state);
        asnMaster.setInsertType(asnData.getInsertType());
        asnMaster.setBillSource(asnData.getBillSource());
        asnMaster.setAsnUdfHs1("1");//标记先发配件入库任务字段
        if (StringUtils.isNotEmpty(asnMaster.getBillNo())) {
            asnMasterService.updateById(asnMaster);
        } else {
            asnMaster.setBillNo(billNo);
            asnMasterService.save(asnMaster);
        }


        //新增detail
        List<AsnDetail> asnDetails = asnData.getAsnDetails();
        for (int i = 0; i < asnDetails.size(); i++) {
            String detailNo = billNo + "-" + (i + 1);
            AsnDetail asnDetail = asnDetails.get(i);
            asnDetail.setBillNo(billNo);
            asnDetail.setId(null);
            asnDetail.setDetailNo(detailNo);
            asnDetailService.save(asnDetail);
            //更新采购单的ASN数量
            String requestDetailDetailNo = asnDetail.getRequestDetailDetailNo();
            RequestBuyDetail requestBuyDetail = requestBuyDetailService.findByDetailNo(requestDetailDetailNo);
            if (requestBuyDetail != null) {
                requestBuyDetail.setAsnQuantity(asnDetail.getExpectQuantity() + requestBuyDetail.getAsnQuantity());
                requestBuyDetailService.updateById(requestBuyDetail);
            }
        }
    }

    @Override
    public List<AsnMasterDto> findList2(AsnMasterCriteria criteria) {
        return asnMasterMapper.findList2(criteria);
    }

    @Override
    public List<AsnMasterDto> findQcList(AsnMasterCriteria criteria) {
        return asnMasterMapper.findQcList(criteria);
    }

    @Override
    public void updateQcState(String billNo, int qcState) {
        asnMasterMapper.updateQcState(billNo,qcState);
    }

    //获取入库单据类型
    public static Integer getAsnType(PurchaseOrderBO  bo){
        PurchaseOrderDetailBO de = bo.getDetails().get(0);
        if(bo.getBillTypeId() == 72 && de.getTargetBillTypeId() == 1){
//            采购入库 24  委外入库  43    产成品入库 58     其他入库  51    调拨入库  59
            return 24;
        }else if (bo.getBillTypeId() == 702 && de.getTargetBillTypeId() == 1){
            return 24;
        }else if (bo.getBillTypeId() == 702 && de.getTargetBillTypeId() == 711){
            return 24;
        }else if (bo.getBillTypeId() == 702 && de.getTargetBillTypeId() == 5){
            return 43;
        }else if (bo.getBillTypeId() == 85 && de.getTargetBillTypeId() == 2){
            return 58;
        }else if (bo.getBillTypeId() == 251300056 && de.getTargetBillTypeId() == 10){
            return 51;
        }else if (bo.getBillTypeId() == 10){
            return 51;
        }else if (bo.getBillTypeId() == 41){
            return 59;
        }else{
            return null;
        }
    }
}

